<template>
  <div class="comprehensive-table-container">
    <el-alert
      :closable="false"
      show-icon
      title="对用户任何举报的处理结果都会记录至“处理记录”，一旦操作无法撤销，请谨慎处理"
      type="warning"
    />
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form
          :inline="true"
          label-width="49px"
          :model="queryForm"
          @submit.prevent
        >
          <el-form-item label="类别">
            <el-select v-model="queryForm.type" placeholder="请选择举报类型">
              <el-option label="全部类型" :value="-1" />
              <el-option label="举报用户" :value="0" />
              <el-option label="举报博客" :value="1" />
              <el-option label="举报评论" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryForm.status" placeholder="请选择举报状态">
              <el-option label="全部状态" :value="-1" />
              <el-option label="未（待）处理" :value="0" />
              <el-option label="通过" :value="1" />
              <el-option label="拒绝" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="检索">
            <el-input
              v-model="queryForm.title"
              placeholder="姓名、手机号或登录账号"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              icon="el-icon-search"
              native-type="submit"
              type="primary"
              @click="queryData"
            >
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
    </vab-query-form>

    <el-table
      ref="tableSortRef"
      v-loading="listLoading"
      border
      :data="list"
      :height="height"
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column
        align="center"
        show-overflow-tooltip
        type="selection"
        width="55"
      />
      <el-table-column
        align="center"
        label="序号"
        show-overflow-tooltip
        width="55"
      >
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="举报发起人"
        prop="handleUserPhone"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        label="举报类型"
        prop="reportType"
        show-overflow-tooltip
        width="80"
      >
        <template #default="{ row }">
          <span v-if="row.reportType === 0" style="color: #006cff">用户</span>
          <span v-else-if="row.reportType === 1" style="color: #42b983">
            博客
          </span>
          <span v-else style="color: #ffba00">评论</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="目标内容"
        min-width="200"
        prop="targetBody"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="被举报人"
        prop="targetUserPhone"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        label="举报原因"
        min-width="150"
        prop="reportReason"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="发起时间"
        prop="reportHandleTime"
        show-overflow-tooltip
        width="150"
      >
        <template #default="{ row }">
          {{ formatDates(row.reportHandleTime) }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="当前状态"
        prop="reportStatus"
        show-overflow-tooltip
        width="80"
      >
        <template #default="{ row }">
          <span v-if="row.reportStatus === 0" style="color: #ffba00">
            待处理
          </span>
          <span v-else-if="row.reportStatus === 1" style="color: #42b983">
            已通过
          </span>
          <span v-else style="color: #f34d37">已驳回</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
        width="80"
      >
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">
            {{ row.reportStatus === 0 ? '处理' : '查看' }}
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <table-edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    computed,
    defineComponent,
    getCurrentInstance,
    onBeforeMount,
    onBeforeUnmount,
    onMounted,
    reactive,
    toRefs,
    watch,
  } from 'vue'
  import { useStore } from 'vuex'
  import { useRouter, useRoute } from 'vue-router'
  import { doDelete, getList } from '@/api/feedback_report'
  import { handleMatched, handleTabs } from '@/utils/routes'
  import TableEdit from './components/TableEdit'
  import moment from 'moment'

  export default defineComponent({
    name: 'ComprehensiveTable',
    components: {
      TableEdit,
    },
    setup() {
      const store = useStore()
      const router = useRouter()
      const route = useRoute()
      const routes = computed(() => store.getters['routes/routes'])
      const changeTabsMeta = (options) =>
        store.dispatch('tabs/changeTabsMeta', options)
      const addVisitedRoute = (options) =>
        store.dispatch('tabs/addVisitedRoute', options)
      const { proxy } = getCurrentInstance()

      const state = reactive({
        editRef: null,
        tableSortRef: null,
        fold: false,
        height: proxy.$baseTableHeight(2) - 30,
        imgShow: true,
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          type: -1,
          status: -1,
        },
      })

      watch(
        () => route.path,
        (value) => {
          if (value === '/system/admin/comprehensiveTable') fetchData()
        }
      )

      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { list, total },
        } = await getList(state.queryForm)
        state.list = list
        const imageList = []
        list.forEach((item) => {
          imageList.push(item.img)
        })
        state.imageList = imageList
        state.total = total
        state.listLoading = false
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const statusFilter = (status) => {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger',
        }
        return statusMap[status === 1 ? 'published' : 'deleted']
      }
      const handleFold = () => {
        state.fold = !state.fold
        handleHeight()
      }
      const handleHeight = () => {
        if (state.fold) state.height = proxy.$baseTableHeight(2) - 47
        else state.height = proxy.$baseTableHeight(3) - 30
      }
      const tableSortChange = () => {
        const imageList = []
        state['tableSortRef'].tableData.forEach((item) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      }
      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const handleAdd = () => {
        state['editRef'].showEdit()
      }
      const handleEdit = (row) => {
        state['editRef'].showEdit(row)
      }
      const handleDelete = (row) => {
        if (row.aid) {
          proxy.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.aid })
            proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.aid).join()
            proxy.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids: ids })
              proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            proxy.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleDetailStayTable = async () => {
        for (let i = 0; i < state.selectRows.length; i++) {
          const matched = handleMatched(routes.value, 'Detail')
          const tab = handleTabs(
            {
              ...matched[matched.length - 1],
              query: state.selectRows[i],
            },
            true
          )
          if (tab) {
            await addVisitedRoute(tab)
            changeTabsMeta({
              title: '详情页',
              meta: {
                title: `${tab.query.title} 详情页`,
              },
            })
          }
        }
      }

      const handleDetail = (row) => {
        if (row.id)
          router.push({
            path: './detail',
            query: row,
          })
        else {
          if (state.selectRows.length === 1) {
            router.push({
              path: '/vab/table/detail',
              query: state.selectRows[0],
            })
          } else {
            proxy.$baseMessage(
              '请选择一行进行详情页跳转',
              'error',
              'vab-hey-message-error'
            )
          }
        }
      }
      const handleMessage = () => {
        proxy.$baseMessage('test1', 'success', false, 'vab-hey-message-success')
      }
      const handleAlert = () => {
        proxy.$baseAlert('11')
        // proxy.$baseAlert('11', '自定义标题', () => {
        //   /* 可以写回调; */
        // })
        // proxy.$baseAlert('11', null, () => {
        //   /* 可以写回调; */
        // })
      }
      const handleConfirm = () => {
        proxy.$baseConfirm(
          '你确定要执行该操作?',
          null,
          () => {
            /* 可以写回调; */
          },
          () => {
            /* 可以写回调; */
          }
        )
      }
      const handleNotify = () => {
        proxy.$baseNotify('测试消息提示', 'test', 'success', 'bottom-right')
      }

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })
      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })
      onMounted(() => {
        fetchData()
      })

      return {
        ...toRefs(state),
        handleSizeChange,
        handleCurrentChange,
        queryData,
        statusFilter,
        handleFold,
        handleHeight,
        tableSortChange,
        setSelectRows,
        handleAdd,
        handleEdit,
        handleDelete,
        handleDetailStayTable,
        handleDetail,
        handleMessage,
        handleAlert,
        handleConfirm,
        handleNotify,
        fetchData,
      }
    },
    methods: {
      formatDates(dateStr) {
        let pattern = 'YYYY-MM-DD HH:mm'
        return moment(parseInt(dateStr + '000')).format(pattern)
      },
    },
  })
</script>
